package com.dp.service.menucontrol;

import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.pub.SysProperty;
import com.dp.service.impl3.BaseImpl;
import com.dp.util.DataMap;
import com.dp.vo.NewsK16Menu;
import com.dp.vo.NewsK16MenuItem;

/**
 * 
 * 项目名称：platform_p2
 * 类名称：MenuItemServiceImpl
 * 类描述：菜单设置service
 * 创建人：Administrator
 * 创建时间：2010-10-28 16:24:26
 * 修改人：Administrator
 * 修改时间：2010-10-28 16:24:26
 * 修改备注：
 * @version 
 * 
 */
@Service
@Transactional
public class MenuServiceImpl extends BaseImpl {
	/**
	 * 发布菜单
	 */
	public void rePublishMenu(NewsK16Menu menu){
		List<String> urlList = new ArrayList<String>();
        String urltemp = SysProperty.getPrep("sysnodeurl_a");	//中心节点url
        if(urltemp==null||"".equals(urltemp)){
        	return;
        }
        urltemp = urltemp.substring(0, urltemp.lastIndexOf(".")) + "!reloadk16menu.do?menuid="+menu.getId(); //http://218.246.23.83:8082/mobileserver/action/server!reloadk16menu.do
        urlList.add(urltemp);
        
        urltemp = SysProperty.getPrep("sysnodeurl_b");	//本节点url
        if(urltemp==null||"".equals(urltemp)){
        	return;
        }
        urltemp = urltemp.substring(0, urltemp.lastIndexOf(".")) + "!reloadk16menu.do?menuid="+menu.getId();
        urlList.add(urltemp);
        
        for (String url : urlList) {
    		try{
    			URL testUrl = new URL(url);
    		    HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
    			conn.setRequestMethod("POST");
    			int ret = conn.getResponseCode();
    			conn.disconnect();
    		    log.info(ret != 200 ? "发布菜单失败："+url : "发布菜单成功："+url);
    		} catch (Exception e) {
    			log.error("发布菜单失败："+url+",Connection refused: connect");}
		}
        
	 }

//	public boolean checkMenu(NewsK16Menu menu)
//	{
//        String sql = "select id from news_k16menu where cname = '"+menu.getCname()+"'";
//		log.info(" checkNewsK16Menu excute sql :" +sql);
//		try {
//			this.init();
//			this.rs1 = this.stmt.executeQuery(sql);
//			if (rs1.next())
//				return true;
//			else
//				return false;
//		} catch (Exception e) {
//			log.info(" checkNewsK16Menu fail !!!" +e.getMessage());
//			e.printStackTrace();
//			return false;
//		} finally{
//			this.closeAll();
//		}
//	}
	
	public int findAllNewsK16MenuCount(DataMap hashMap) {
		String cname = (String)hashMap.get("cname");
		Integer isdefault = (Integer)hashMap.get("isdefault");
		Integer lastversion = (Integer)hashMap.get("lastversion");
		String sql = "SELECT count(id) FROM news_k16menu where 1=1 ";
		if (cname != null && !"".equals(cname)) {
			sql += " and cname like '%" + cname + "%'";
		}
		if (isdefault != null) {
			sql += " and isdefault =" + isdefault;
		}
		if (lastversion != null) {
			sql += " and lastversion =" + lastversion;
		}
		int count =0;
		try {
			log.info(" findAllNewsK16MenuCount excute sql: " +sql);
			count = this.getOneInt();
		} catch (Exception e) {
			log.error(" findAllNewsK16MenuCount fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return (count);
	}
	
	public List<NewsK16Menu> findAllNewsK16Menu(DataMap hashMap, int firstrow, int maxrow) {
		JsonPage jpage=(JsonPage)hashMap.get("jpage");
		String cname = (String)hashMap.get("cname");
		Integer isdefault = (Integer)hashMap.get("isdefault");
		Integer lastversion = (Integer)hashMap.get("lastversion");
		String sql = "SELECT id,cname,isdefault,note,lastversion FROM news_k16menu where 1=1 ";
		if (cname != null && !"".equals(cname)) {
			sql += " and cname like '%" + cname + "%'";
		}
		if (isdefault != null) {
			sql += " and isdefault =" + isdefault;
		}
		if (lastversion != null) {
			sql += " and lastversion =" + lastversion;
		}
		if (jpage != null && jpage.getSidx() != null
				&& !"".equals(jpage.getSidx())) {
			sql += " order by " + jpage.getSidx();
			sql += " " + jpage.getSord();
		}
		if (jpage != null){
			sql += " limit " +firstrow+","+maxrow;
		}
		List<NewsK16Menu> result = new ArrayList<NewsK16Menu>();
		try {
			
			log.info(" findAll NewsK16Menu excute sql: " +sql);
			List<Object[]> tempp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:tempp)
			{
				NewsK16Menu one = new NewsK16Menu();
				one.setId(this.getInteger(o[0]));
				one.setCname(this.getString(o[1]));
				one.setIsdefault(this.getInteger(o[2]));
				one.setNote(this.getString(o[3]));
				one.setLastversion(this.getInteger(o[4]));
				result.add(one);
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 菜单lastversion(最新版本号) +1
	 * @param menu
	 * @return
	 */
	public boolean addNewsK16MenuLastversion(NewsK16Menu menu)
	{
		try {
			
			sql=("SELECT MAX(lastversion) FROM news_k16menu");
			
			int lastversion = 0;	//最新菜单版本号
		
				lastversion =this.getOneInt();
			sql = "update news_k16menu set lastversion = "+(lastversion+1)+" where id ="+menu.getId();
	        log.info(" update NewsK16Menu excute sql :" +sql);
			this.em.createNativeQuery(sql).executeUpdate();
			return true;
		} catch (Exception e) {
			log.error(" update NewsK16Menu fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	//设为默认菜单
	public boolean updateNewsK16MenuSetDefault(NewsK16Menu menu)
	{
		ArrayList<String> batchSql = new ArrayList<String>();
		batchSql.add("update news_k16menu set isdefault = 1 where isdefault = 0");
		batchSql.add("update news_k16menu set isdefault = 0 where id ="+menu.getId());
		try {
			return execTransaction(batchSql);
		} catch (Exception e) {
			log.error(" update NewsK16Menu SetDefault fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean addNewsK16Menu(NewsK16Menu menu, String menuitemids)
	{
		try {
			sql=("SELECT COUNT(1) FROM news_k16menu");
			int isdefault = 0;	//第一条数据为默认菜单
			if (this.getOneInt()>0){
				isdefault = 1;
			}
			sql = "INSERT INTO news_k16menu(cname, isdefault, note, lastversion) VALUES('"+menu.getCname()+"', "+isdefault+", '"+menu.getNote()+"', 0)";
			this.em.createNativeQuery(sql).executeUpdate();
			if (menuitemids != null && !"".equals(menuitemids)){
				String[] menuitemidsArray = menuitemids.split(",");
				sql=("SELECT @@identity");
				int menuId = this.getOneInt();
	
				sql=("insert into news_k16menuitemorder(menuid, menuitemid, menuorder) values(?,?,?)");
				int i = 1;
				Query	query=em.createNativeQuery(sql);
				
				for (String menuitemid : menuitemidsArray) {
					query.setParameter(1, menuId);
					query.setParameter(2, Integer.parseInt(menuitemid));
					query.setParameter(3, i);
					query.executeUpdate();
				}
			}
		
			return true;
		} catch (Exception e) {
			log.error(" add NewsK16Menu fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean updateNewsK16Menu(NewsK16Menu menu, String menuitemids)
	{
		ArrayList<String> batchSql = new ArrayList<String>();
        String sql = "update news_k16menu set cname = '"+menu.getCname()+"', note = '"+
        				menu.getNote()+"' where id ="+menu.getId();
		batchSql.add(sql);
		
		//保存菜单项与菜单的关系
		batchSql.add("delete from news_k16menuitemorder where menuid="+menu.getId()+"");	//先删除已存在的

		if (menuitemids != null && !"".equals(menuitemids)){
			String[] menuitemidsArray = menuitemids.split(",");
			int i = 1;
			for (String menuitemid : menuitemidsArray) {
				batchSql.add("insert into news_k16menuitemorder(menuid, menuitemid, menuorder) values("+menu.getId()+","+menuitemid+","+i+")");
				i++;
			}
		}
		try {
			return execTransaction(batchSql);
		} catch (Exception e) {
			log.error(" update NewsK16Menu fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean insertNewsK16MenuItem(NewsK16MenuItem menuItem)
	{
		boolean result = false;
        sql = "insert into news_k16menuitem(itemname, itemtext, normalicon, focusicon, appid, appparam, apptype) values(?,?,?,?,?,?,?)";
        log.info(" insert NewsK16MenuItem excute sql :" +sql);
		try {
			Query	query=em.createNativeQuery(sql);
			
				query.setParameter(1, menuItem.getItemname());
				query.setParameter(2, menuItem.getItemtext());
				query.setParameter(3, menuItem.getNormalicon());
				query.setParameter(4, menuItem.getFocusicon());
				query.setParameter(5, menuItem.getAppid());
				query.setParameter(6, menuItem.getAppparam());
				query.setParameter(7, menuItem.getApptype());
			result = query.executeUpdate()>0;
		} catch (Exception e) {
			log.error(" insert NewsK16MenuItem fail !!!" +e.getMessage());
			e.printStackTrace();
		} 
		return result;
	}
	
	public boolean updateNewsK16MenuItem(NewsK16MenuItem menuItem)
	{
        String sql = "update news_k16menuitem set itemname = '"+menuItem.getItemname()+"', itemtext = '"+menuItem.getItemtext()+"', " ;
        if (menuItem.getNormalicon()!=null && !"".equals(menuItem.getNormalicon()))
        	sql += "normalicon = '"+menuItem.getNormalicon()+"', ";
        if (menuItem.getFocusicon()!=null && !"".equals(menuItem.getFocusicon()))
        	sql += "focusicon = '"+menuItem.getFocusicon()+"', ";
        sql += " appid = "+menuItem.getAppid()+", appparam = '"
				        +menuItem.getAppparam()+"', apptype = '"+menuItem.getApptype()+"', appparam1 = '"+menuItem.getAppparam1()+"', appparam2 = '"
				        +menuItem.getAppparam2()+"' where id ="+menuItem.getId();
        log.info(" update NewsK16MenuItem excute sql :" +sql);
		try {
			return this.execUpdate(sql);
		} catch (Exception e) {
			log.error(" update NewsK16MenuItem fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public int findAllNewsK16MenuItemCount(DataMap hashMap) {
		Integer menuid = (Integer)hashMap.get("menuid");
		String itemname = (String)hashMap.get("itemname");
		String itemtext = (String)hashMap.get("itemtext");
		Integer appid = (Integer)hashMap.get("appid");
		String appparam = (String)hashMap.get("appparam");
		String apptype = (String)hashMap.get("apptype");
		String sql = "SELECT count(mi.id) FROM news_k16menuitem mi";
		if (menuid != null) {
			sql += ",news_k16menuitemorder mio where mi.id=mio.menuitemid and mio.menuid = " + menuid;
		}else {
			sql += " where 1=1 ";
		}
		if (itemname != null && !"".equals(itemname)) {
			sql += " and mi.itemname like '%" + itemname + "%'";
		}
		if (itemtext != null && !"".equals(itemtext)) {
			sql += " and mi.itemtext like '%" + itemtext + "%'";
		}
		if (appid != null) {
			sql += " and mi.appid = " + appid;
		}
		if (appparam != null && !"".equals(appparam)) {
			sql += " and mi.appparam like '%" + appparam + "%'";
		}
		if (apptype != null && !"".equals(apptype)) {
			sql += " and mi.apptype like '" + apptype + "'";
		}
		int count =0;
		try {
			log.info(" findAllNewsK16MenuItemCount excute sql: " +sql);
			count =this.getOneInt();
		} catch (Exception e) {
			log.error(" findAllNewsK16MenuItemCount fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return (count);
	}
	
	public List<NewsK16MenuItem> findAllNewsK16MenuItem(DataMap hashMap, int firstrow, int maxrow) {
		Integer menuid = (Integer)hashMap.get("menuid");
		JsonPage jpage=(JsonPage)hashMap.get("jpage");
		String itemname = (String)hashMap.get("itemname");
		String itemtext = (String)hashMap.get("itemtext");
		Integer appid = (Integer)hashMap.get("appid");
		String appparam = (String)hashMap.get("appparam");
		String apptype = (String)hashMap.get("apptype");
		String sql = "SELECT mi.id,itemname,itemtext,normalicon,focusicon,appid,appparam,apptype FROM news_k16menuitem mi ";
		if (menuid != null) {
			sql += ",news_k16menuitemorder mio where mi.id=mio.menuitemid and mio.menuid = " + menuid;
		}else {
			sql += " where 1=1 ";
		}
		if (itemname != null && !"".equals(itemname)) {
			sql += " and mi.itemname like '%" + itemname + "%'";
		}
		if (itemtext != null && !"".equals(itemtext)) {
			sql += " and mi.itemtext like '%" + itemtext + "%'";
		}
		if (appid != null) {
			sql += " and mi.appid = " + appid;
		}
		if (appparam != null && !"".equals(appparam)) {
			sql += " and mi.appparam like '%" + appparam + "%'";
		}
		if (apptype != null && !"".equals(apptype)) {
			sql += " and mi.apptype like '" + apptype + "'";
		}
		if (menuid != null) {
			sql += " order by mio.menuorder asc";
		}else {
			if (jpage != null && jpage.getSidx() != null
					&& !"".equals(jpage.getSidx())) {
				sql += " order by mi." + jpage.getSidx();
				sql += " " + jpage.getSord();
			}
		}
		if (jpage != null){
			sql += " limit " +firstrow+","+maxrow;
		}
		List<NewsK16MenuItem> result = new ArrayList<NewsK16MenuItem>();
		try {
			
			log.info(" findAll NewsK16MenuItem excute sql: " +sql);
			List<Object[]> tempp=this.em.createNativeQuery(sql).getResultList();
			for(Object[]o:tempp)
			{
				NewsK16MenuItem one = new NewsK16MenuItem();
				one.setId(this.getInteger(o[0]));
				one.setItemname(this.getString(o[1]));
				one.setItemtext(this.getString(o[2]));
				one.setNormalicon(this.getString(o[3]));
				one.setFocusicon(this.getString(o[4]));
				one.setAppid(this.getInteger(o[5]));
				one.setAppparam(this.getString(o[6]));
				one.setApptype(this.getString(o[7]));
				result.add(one);
			}
		
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
	}
	
	public NewsK16MenuItem getNewsK16MenuItemById(NewsK16MenuItem menuItem) {
		String sql = "SELECT mi.id,itemname,itemtext,normalicon,focusicon,appid,appparam,apptype FROM news_k16menuitem mi where id = "+menuItem.getId();
		NewsK16MenuItem one = null;
		try {
//			this.init();
//			log.info(" findAll NewsK16MenuItem excute sql: " +sql);
//			this.rs1 = this.stmt.executeQuery(sql);
//			if(rs1.next()){
//				one = new NewsK16MenuItem();
//				one.setId(rs1.getInt(1));
//				one.setItemname(rs1.getString(2));
//				one.setItemtext(rs1.getString(3));
//				one.setNormalicon(rs1.getString(4));
//				one.setFocusicon(rs1.getString(5));
//				one.setAppid(rs1.getInt(6));
//				one.setAppparam(rs1.getString(7));
//				one.setApptype(rs1.getString(8));
//			}
			List a=this.getObjectList(sql, NewsK16MenuItem.class);
			one=(a.size()>0?(NewsK16MenuItem)a.get(0):null);
			return one;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
	}
	
	/**
	 * 新增时判断此菜单项名称是否已存在
	 * @param itemname
	 * @return
	 */
	public boolean checkItemname(String itemname) {
		boolean b=false;
		try {
			
			sql="SELECT count(*) FROM news_k16menuitem n WHERE n.itemname='"+itemname+"'";
			b=(this.getOneInt()>0);
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
		return b;
	}
	
	/**
	 * 修改时判断新变化菜单项名称是否已存在
	 * @param itemname
	 * @return
	 */
	public boolean checkItemname2(String itemname,String itemnameO) {
		boolean b=false;
		try {
			sql="SELECT count(*) FROM news_k16menuitem n WHERE n.itemname='"+itemname+"' AND n.itemname!='"+itemnameO+"'";
			b=(this.getOneInt()>0);
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
		return b;
	}
	
}